package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.PageResult;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.AddressBook;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.entity.User;
import com.itheima.mapper.OrderMapper;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单实现类
 */
@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    //订单详情表业务接口
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 下单
     *
     * @param orders
     */
    @Override
    public void save(Orders orders, HttpSession session) {
        log.debug("**下单**",orders.toString());
        User user = (User)session.getAttribute("user");
        //1 补全orders表中数据
        //1.1获取唯一的订单号 设置到orders表中number字段
        orders.setNumber(IdWorker.getId()+"");
        //1.2下单设置 2待派送    //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //1.3 下单用户id userId 可以从ThreadLocal中获取当前用户id
        orders.setUserId(user.getId());
        //1.4 addressBookId payMethod amount remark(页面上传入的数据)
        //1.5 orderTime 设置当前时间为下单时间
        orders.setOrderTime(LocalDateTime.now());
        //1.6 checkoutTime 设置当前时间为结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7 userName user表中name值
        orders.setUserName(user.getName());
        //1.8 phone address consignee address_book地址薄表中phone手机号  address地址  consignee收货人名字
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());//收货人手机号
        orders.setAddress(addressBook.getDetail());//收货地址 实际项目中应该 将省市区拼接+详细信息
        orders.setConsignee(addressBook.getConsignee());//收货人
        log.debug("**保存订单数据**",orders.toString());
        //2 保存订单数据到orders表中
        orderMapper.insert(orders);
        Long ordersId = orders.getId();///订单表主键id 设置到订单详情表中orderId
        log.debug("**订单保存成功了**订单主键id为{}**",ordersId);
        //3 保存订单详情到order_detail表中
        orderDetailService.insert(ordersId);
        log.debug("**订单详情表保存成功了**");
    }

    /**
     * 移动端-历史订单/最新订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<OrdersDto> userPage(Long page, Long pageSize) {
        //1.创建查询对象
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();

        //2.1 只查询当前用户的订单
        qw.eq(Orders::getUserId, BaseContext.getCurrentId());

        //2.2.按照最新订单时间最前排序
        qw.orderByDesc(Orders::getOrderTime);

        //3.创建分页查询对象，并添加页码和每页条数
        Page resultPage = new Page(page, pageSize);

        //4.分页查询
        orderMapper.selectPage(resultPage, qw);

        //5.订单分页数据
        List<Orders> records = resultPage.getRecords();


        //6.将 List<Orders> 转成 List<OrdersDto>
        List<OrdersDto> ordersDtoList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(records)) {
            ordersDtoList = records.stream().map(item -> {
                OrdersDto ordersDto = new OrdersDto();
                //拷贝数据到 ordersDto
                BeanUtils.copyProperties(item, ordersDto);
                //根据 odersId 得到 订单详情列表，并添加到 ordersDto
                List<OrderDetail> orderDetailList = orderDetailService.listByOdersId(item.getId());
                ordersDto.setOrderDetails(orderDetailList);

                return ordersDto;
            }).collect(Collectors.toList());
        }

        //7.重新设置 resultPage 的 records
        resultPage.setRecords(ordersDtoList);

        //8.封装数据并返回
        return new PageResult<>(resultPage.getTotal(), resultPage.getRecords());
    }

    /**
     * 订单分页查询
     */
    @Override
    public PageResult<Orders> list(Long page, Long pageSize, String number, Date beginTime, Date endTime) {
        //new Page(page,pageSize)
        Page pp = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //时间查询
        lambdaQueryWrapper.ge(beginTime!=null,Orders::getOrderTime,beginTime);
        lambdaQueryWrapper.le(endTime!=null,Orders::getOrderTime,endTime);
        //订单查询
        lambdaQueryWrapper.like(number!=null,Orders::getNumber,number);
        //按下单时间升序
        lambdaQueryWrapper.orderByAsc(Orders::getOrderTime);
        orderMapper.selectPage(pp,lambdaQueryWrapper);
        //2.3 将page对象中total records 封装到PageResult对象中
        log.debug("订单总记录数{}，当前页面数据{}", pp.getTotal(), pp.getRecords());

        return new PageResult<>(pp.getTotal(),pp.getRecords());
    }

    /**
     * 订单状态派送/完成
     */
    @Override
    public void updateOrder(Orders orders, HttpSession session) {
        Integer status = orders.getStatus();
        Long id = orders.getId();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getId,id);
        Orders ordersStatus = new Orders();
        ordersStatus.setStatus(status);
        orderMapper.update(ordersStatus,lambdaQueryWrapper);
    }
}
